package com.by.filter;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSignerUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;

//@Component
@Slf4j
//配置优先执行值越小越先执行
//@Order(1)
public class TokenFilter implements GlobalFilter {
    @Value("${cn.smart.tokenx.key}")
    private String tokenKey;
    private static List<String> whiteList = CollUtil.newArrayList("/api/login", "/api/register");
//    @Value("${cn.smart.tokenx.excludePathPatterns}")
//    private List<String> whiteList;




    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        URI uri = request.getURI();
        String path = uri.getPath().toLowerCase().trim();
        //排除白名单的验证
        if(whiteList.contains(path)){
            return chain.filter(exchange);
        }
        ServerHttpResponse response = exchange.getResponse();
        List<String> tokens = request.getHeaders().get("token");
        //验证的是有没有传token
        if (ObjectUtil.isEmpty(tokens)){
            log.error("请传token");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        String token = tokens.get(0);

        //验证的是传的token值是否为空
        if(ObjectUtil.isEmpty(token)){
            log.error("token 不能为空");
           response.setStatusCode(HttpStatus.UNAUTHORIZED);
           return response.setComplete();
        }
        boolean b = false;
        // 验证算法，JWTValidator包含过期的验证，验证比较全面
        try {
            JWTValidator.of(token).validateAlgorithm(JWTSignerUtil.hs256(tokenKey.getBytes())).validateDate();
            b = true;
        }catch (Exception ex){
            ex.printStackTrace();
            log.error("token 过期");
        }
        if(!b){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

//接着执行下面的过滤器,token还会带到下游，我们的服务还是要用我们之前的token-starter,token-starter功能只保留解析token写入Threadlocal，验证的功能不再需要
        return chain.filter(exchange);
    }
}
